﻿using Microsoft.Hadoop.WebHDFS;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ViewMaker.Core;
using ViewMaker.Core.Controls;

namespace HDInsightStudio
{
    public class FolderItem : TreeItem
    {
        [Browsable(false)]
        public string Path { get; private set; }

        private WebHDFSClient hdfs;

        public FolderItem(TreeItem parent, string path, WebHDFSClient hdfs)
            : base(parent)
        {
            Path = path;
            this.hdfs = hdfs;
        }

        [Browsable(false)]
        public override string Name
        {
            get { return Path == null ? null : Path.Split('/').Last(); }
        }

        [Browsable(true)]
        [View(ViewControlType.DataGrid)]
        [ViewProperty(DataGridViewControl.Properties.SelectedItem, "CurrentItem")]
        public ObservableCollection<FileItem> Files 
        {
            get
            {
                if (_files == null)
                {
                    _files = new ObservableCollection<FileItem>();
                }
                return _files;
            }
        }
        private ObservableCollection<FileItem> _files;


        public FileItem CurrentItem
        {
            get { return _currentItem; }
            set { _currentItem = value; OnPropertyChanged("CurrentItem"); }
        }
        private FileItem _currentItem;

        public async void GetFolderStatus(bool force = false)
        {
            if (GetFolderStatusExecuted && !force) return;
            Files.Clear();
            Children.Clear();
            GetFolderStatusExecuted = true;
            var folder = Path == "/" ? "/" : Path + "/";
            var entry = await hdfs.GetDirectoryStatus(folder);            
            foreach (var item in entry.Files)
            {
                var file = new FileItem(this, "/" + item.PathSuffix, item.Length, hdfs);
                Files.Add(file);
            }
            foreach (var item in entry.Directories)
            {
                Children.Add(new FolderItem(this, "/" + item.PathSuffix, hdfs));
            }
        }
        private bool GetFolderStatusExecuted = false;
    }
}
